package com.lft.com.oilgas.controller;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.sdk.service.ocr_api20210707.AsyncClient;
import com.aliyun.sdk.service.ocr_api20210707.models.*;
import com.google.gson.Gson;
import com.lft.com.oilgas.config.aliOSSProperties;
import com.lft.com.oilgas.util.Result;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/ocr")
public class OcrController {

    @Autowired
    private aliOSSProperties aliOSSProperties;

    // 前端发送正反面图片 URL，请求身份证识别
    @RequestMapping ("/recognizeIdCard")
    public Result recognizeIdCard(@RequestBody Map<String, String> map) throws Exception {
        System.out.println(map);
        // 获取前端传递的正反面图片 URL
        String frontImageUrl = map.get("frontImageUrl");
        String backImageUrl = map.get("backImageUrl");

        // 调用 OCR 身份证识别方法，识别正面和反面
        String frontOcrResult = recognizeIdCard(frontImageUrl, "face");
        String backOcrResult = recognizeIdCard(backImageUrl, "back");
        Map map1 = new HashMap();
        map1.put("frontOcrResult", frontOcrResult);
        map1.put("backOcrResult", backOcrResult);
        System.out.println(map1);
        // 将识别结果封装为 JSON 返回给前端
        return new Result(true,map1);
    }

    // OCR 身份证识别方法
    private String recognizeIdCard(String imageUrl, String side) throws Exception {
        // 配置阿里云 OCR 凭证
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliOSSProperties.getAccessKeyId())
                .accessKeySecret(aliOSSProperties.getAccessKeySecret())
                .build());

        // 创建 OCR 客户端
        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create()
                        .setEndpointOverride("ocr-api.cn-hangzhou.aliyuncs.com"))
                .build();

        // 设置 OCR 请求参数
        RecognizeIdcardRequest recognizeIdcardRequest = RecognizeIdcardRequest.builder()
                .url(imageUrl)  // 前端传来的图片 URL
                .build();

        // 异步获取 OCR API 请求的返回值
        CompletableFuture<RecognizeIdcardResponse> response = client.recognizeIdcard(recognizeIdcardRequest);

        // 同步获取 OCR 结果
        RecognizeIdcardResponse resp = response.get();

        // 返回识别结果
        return new Gson().toJson(resp);
    }

    @RequestMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()+"-"+originalFilename;
        OSS ossClient = new
                OSSClientBuilder().build(aliOSSProperties.getEndpoint(),
                aliOSSProperties.getAccessKeyId(),
                aliOSSProperties.getAccessKeySecret());
        ossClient.putObject(aliOSSProperties.getBucketName(),
                newName, inputStream);
        //文件访问路径
        String url = aliOSSProperties.getEndpoint().split("//")[0] + "//" + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndpoint().split("//")[1] + "/" + newName;
        System.out.println(url);
        ossClient.shutdown();
        return new Result(true,url);
    }
    // 前端发送图片 URL，请求驾驶证识别
    @RequestMapping("/recognizeDrivingLicense")
    public Result recognizeDrivingLicense(@RequestBody Map<String, String> map) throws Exception {
        System.out.println(map);

        // 获取图片 URL
        String imageUrl = map.get("imageUrl");
        if (imageUrl == null || imageUrl.isEmpty()) {
            return new Result(false, "图片URL不能为空");
        }

//         调用驾驶证识别方法
        String result = recognizeDrivingLicense(imageUrl);

        Map<String, Object> map1 = new HashMap<>();
        map1.put("recognitionResult", result);

        return new Result(true, map1);
    }

    // OCR 驾驶证识别方法
    private String recognizeDrivingLicense(String imageUrl) throws Exception {
        // 配置阿里云 OCR 凭证
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliOSSProperties.getAccessKeyId())
                .accessKeySecret(aliOSSProperties.getAccessKeySecret())
                .build());

        // 创建 OCR 客户端
        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create()
                        .setEndpointOverride("ocr-api.cn-hangzhou.aliyuncs.com"))
                .build();

        // 设置 OCR 请求参数
        RecognizeDrivingLicenseRequest recognizeDrivingLicenseRequest = RecognizeDrivingLicenseRequest.builder()
                .url(imageUrl)  // 前端传来的图片 URL
                .build();

        // 异步获取 OCR API 请求的返回值
        CompletableFuture<RecognizeDrivingLicenseResponse> response = client.recognizeDrivingLicense(recognizeDrivingLicenseRequest);

        // 同步获取 OCR 结果
        RecognizeDrivingLicenseResponse resp = response.get();

        // 返回识别结果
        return new Gson().toJson(resp);
    }
    // 前端发送图片 URL，请求行驶证识别
    @RequestMapping("/recognizeVehicleLicense")
    public Result recognizeVehicleLicense(@RequestBody Map<String, String> map) throws Exception {
        System.out.println(map);

        // 获取图片 URL
        String imageUrl = map.get("imageUrl");
        if (imageUrl == null || imageUrl.isEmpty()) {
            return new Result(false, "图片URL不能为空");
        }

        // 调用行驶证识别方法
        String result = recognizeVehicleLicense(imageUrl);

        Map<String, Object> map1 = new HashMap<>();
        map1.put("recognitionResult", result);

        return new Result(true, map1);
    }

    // OCR 行驶证识别方法
    private String recognizeVehicleLicense(String imageUrl) throws Exception {
        // 配置阿里云 OCR 凭证
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliOSSProperties.getAccessKeyId())
                .accessKeySecret(aliOSSProperties.getAccessKeySecret())
                .build());

        // 创建 OCR 客户端
        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create()
                        .setEndpointOverride("ocr-api.cn-hangzhou.aliyuncs.com"))
                .build();

        // 设置 OCR 请求参数
        RecognizeVehicleLicenseRequest recognizeVehicleLicenseRequest = RecognizeVehicleLicenseRequest.builder()
                .url(imageUrl)  // 前端传来的图片 URL
                .build();

        // 异步获取 OCR API 请求的返回值
        CompletableFuture<RecognizeVehicleLicenseResponse> response = client.recognizeVehicleLicense(recognizeVehicleLicenseRequest);

        // 同步获取 OCR 结果
        RecognizeVehicleLicenseResponse resp = response.get();

        // 返回识别结果
        return new Gson().toJson(resp);
    }
    // 前端发送图片 URL，请求营业执照识别
    @RequestMapping("/recognizeBusinessLicense")
    public Result recognizeBusinessLicense(@RequestBody Map<String, String> map) throws Exception {
        System.out.println(map);

        // 获取图片 URL
        String imageUrl = map.get("imageUrl");
        if (imageUrl == null || imageUrl.isEmpty()) {
            return new Result(false, "图片URL不能为空");
        }

        // 调用营业执照识别方法
        String result = recognizeBusinessLicense(imageUrl);

        Map<String, Object> map1 = new HashMap<>();
        map1.put("recognitionResult", result);
        return new Result(true, map1);
    }

    // OCR 营业执照识别方法
    private String recognizeBusinessLicense(String imageUrl) throws Exception {
        // 配置阿里云 OCR 凭证
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliOSSProperties.getAccessKeyId())
                .accessKeySecret(aliOSSProperties.getAccessKeySecret())
                .build());

        // 创建 OCR 客户端
        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create()
                        .setEndpointOverride("ocr-api.cn-hangzhou.aliyuncs.com"))
                .build();

        // 设置 OCR 请求参数
        RecognizeBusinessLicenseRequest recognizeBusinessLicenseRequest = RecognizeBusinessLicenseRequest.builder()
                .url(imageUrl)  // 前端传来的图片 URL
                .build();

        // 异步获取 OCR API 请求的返回值
        CompletableFuture<RecognizeBusinessLicenseResponse> response = client.recognizeBusinessLicense(recognizeBusinessLicenseRequest);

        // 同步获取 OCR 结果
        RecognizeBusinessLicenseResponse resp = response.get();

        // 返回识别结果
        return new Gson().toJson(resp);
    }

    // 前端发送图片 URL，请求银行开户许可证识别
    @RequestMapping("/recognizeBankAccountLicense")
    public Result recognizeBankAccountLicense(@RequestBody Map<String, String> map) throws Exception {
        System.out.println(map);

        // 获取图片 URL
        String imageUrl = map.get("imageUrl");
        if (imageUrl == null || imageUrl.isEmpty()) {
            return new Result(false, "图片URL不能为空");
        }

        // 调用银行开户许可证识别方法
        String result = recognizeBankAccountLicense(imageUrl);

        Map<String, Object> map1 = new HashMap<>();
        map1.put("recognitionResult", result);

        return new Result(true, map1);
    }

    // OCR 银行开户许可证识别方法
    private String recognizeBankAccountLicense(String imageUrl) throws Exception {
        // 配置阿里云 OCR 凭证
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliOSSProperties.getAccessKeyId())
                .accessKeySecret(aliOSSProperties.getAccessKeySecret())
                .build());

        // 创建 OCR 客户端
        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create()
                        .setEndpointOverride("ocr-api.cn-hangzhou.aliyuncs.com"))
                .build();

        // 设置 OCR 请求参数
        RecognizeBankAccountLicenseRequest recognizeBankAccountLicenseRequest = RecognizeBankAccountLicenseRequest.builder()
                .url(imageUrl)  // 前端传来的图片 URL
                .build();

        // 异步获取 OCR API 请求的返回值
        CompletableFuture<RecognizeBankAccountLicenseResponse> response = client.recognizeBankAccountLicense(recognizeBankAccountLicenseRequest);

        // 同步获取 OCR 结果
        RecognizeBankAccountLicenseResponse resp = response.get();

        // 返回识别结果
        return new Gson().toJson(resp);
    }



}
